<template>
	<PageTemplate title="消息">
    <template #default>
      <scroll-view 
        class="scroll-container"
        scroll-y="true"
        :refresher-enabled="true"
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
        enable-flex="true"
      >
        <view class="chat-list" v-if="!showChatWindow">
          <view 
            v-for="chat in chatList" 
            :key="chat.chat_id"
            class="chat-item"
            @click="openChat(chat)"
          >
            <image 
              class="avatar" 
              :src="chat.other_user.avatar || defaultAvatar"
              mode="aspectFill"
            ></image>
            <view class="chat-info">
              <text class="user-name">{{chat.user.name}} - {{ chat.other_user.name }}</text>
              <text class="last-message">{{ chat.last_message }}</text>
            </view>
            <text class="chat-time">{{ formatChatTime(chat.updatedAt) }}</text>
            <view v-if="chat.unread_count > 0" class="unread-badge">
              {{ chat.unread_count }}
            </view>
          </view>
          
          <view v-if="chatList.length === 0" class="empty-chat">
            <text class="empty-text">暂无聊天记录</text>
          </view>
        </view>
      </scroll-view>
      
      <!-- 聊天窗口 -->
      <view class="chat-window-overlay" v-if="showChatWindow">
        <ChatWindow 
          :other-user="selectedChat.other_user"
          :chat-id="selectedChat.chat_id"
          @close="closeChat"
        />
      </view>
    </template>
  </PageTemplate>
</template>

<script setup>
	import { ref, watch, onMounted } from 'vue';
	import { onShow } from '@dcloudio/uni-app';
	import PageHeader from '@/components/PageHeader.vue';
  import PageTemplate from '@/components/PageTemplate.vue';
	import ChatWindow from '@/components/ChatWindow.vue';
	import { getPrivateChatList } from '@/api/user/privateChat';
	import { formatTime, parseDate, getUserInfo } from '@/utils/index';
	import { usePrivateChatStore } from '@/stores/privateChat';
	import websocket from '@/utils/websocket';
	
	const chatList = ref([]);
	const showChatWindow = ref(false);
	const selectedChat = ref({});
	const defaultAvatar = '/static/logo.png';
	const refreshing = ref(false); // 下拉刷新状态

	// 获取 store 实例
	const privateChatStore = usePrivateChatStore();

	// 获取聊天列表
	const fetchChatList = async () => {
		try {
			const res = await getPrivateChatList();
			if (res.code === 200) {
				// 获取当前用户ID
				const userInfo = getUserInfo();
				const currentUserId = userInfo ? userInfo.user_id : null;
				
				// 后端返回的数据结构是数组 [{chat_id, other_user, updatedAt}]
				chatList.value = res.data.map(chat => {
					// 获取该聊天的未读消息数
					const messages = privateChatStore.getPrivateMessages(chat.chat_id);
					const unreadCount = messages.filter(msg => 
						msg.receiver_id === currentUserId && // 只统计发送给当前用户的消息
						msg.status !== 'read' // 状态不是已读
					).length;
					
					// 获取最后一条消息
					const lastMessage = messages.length > 0 
						? messages[messages.length - 1].content 
						: '暂无消息';
					
					return {
						...chat,
						last_message: lastMessage,
						unread_count: unreadCount
					};
				});
			}
		} catch (error) {
			console.error('获取聊天列表异常:', error);
		} finally {
			// 停止下拉刷新状态
			refreshing.value = false;
		}
	};
	
	// 监听私聊消息变化，实时更新聊天列表
	watch(() => privateChatStore.privateChats, () => {
		// 只有在聊天窗口未打开且在当前页面时才更新列表
		if (!showChatWindow.value) {
			fetchChatList();
		}
	}, { deep: true });
	
	// 监听WebSocket消息，实时更新未读数
	const handleWebSocketMessage = (data) => {
		if (data.type === 'private_message') {
			// 当收到新私聊消息时，更新聊天列表
			fetchChatList();
		}
	};
	
	// 下拉刷新
	const onRefresh = async () => {
		if (refreshing.value) return;
		refreshing.value = true;
		await fetchChatList();
	};
	
	// 打开聊天窗口
	const openChat = (chat) => {
		selectedChat.value = chat;
		showChatWindow.value = true;
	};
	
	// 关闭聊天窗口
	const closeChat = () => {
		showChatWindow.value = false;
		selectedChat.value = {};
		// 重新获取聊天列表以更新未读数等信息
		fetchChatList();
	};
	
	// 格式化聊天时间
	const formatChatTime = (time) => {
		return formatTime(parseDate(time), 'MM-DD HH:mm:ss');
	};
	
	// 页面显示时获取聊天列表
  onMounted(() => {
		// 注册WebSocket消息回调
		websocket.registerCallback(handleWebSocketMessage);
		fetchChatList();
	});
</script>

<style>
	.scroll-container {
		overflow: auto;
		padding: 0 20rpx;
		height: calc(100% - var(--window-top));
	}
	
	.chat-list {
		padding: 0; /* 已在外层容器设置了padding */
	}
	
	.chat-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
		background-color: #fff;
		margin-bottom: 10rpx;
		border-radius: 10rpx;
		position: relative;
	}
	
	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}
	
	.chat-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}
	
	.user-name {
		font-size: 30rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.last-message {
		font-size: 26rpx;
		color: #999;
	}
	
	.chat-time {
		font-size: 24rpx;
		color: #999;
	}
	
	.unread-badge {
		position: absolute;
		right: 20rpx;
		top: 20rpx;
		background-color: #ff3b30;
		color: white;
		border-radius: 50%;
		width: 36rpx;
		height: 36rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
	}
	
	.empty-chat {
		text-align: center;
		padding: 100rpx 0;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
	
	.chat-window-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 1000;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>